package cn.johnyu.netdemo01;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void startServer(View view){
        new Thread(){
            @Override
            public void run() {
                try {
                    ServerSocket server = new ServerSocket(4444);

                    while (true) {
                        Socket sk = server.accept();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                        String line = reader.readLine();
                        Log.i("john", line);
                        OutputStream out = sk.getOutputStream();
                        out.write(("hello" + line).getBytes());
                        reader.close();
                        out.close();
                        sk.close();
                    }
                }
                catch (Exception e){}
            }
        }.start();
    }

    public void sendToServer(View view) {
        new Thread(){
            @Override
            public void run() {
                try {
                    Socket sk = new Socket("172.30.222.1", 4444);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                    OutputStream out = sk.getOutputStream();
                    out.write("I am From LG!\n".getBytes());
                    String line=reader.readLine();
                    Log.i("john","line:...."+line);
                    out.close();
                    sk.close();
                }
                catch (Exception e){}

            }
        }.start();

    }
}
